<?php 
namespace App\Console\Commands;

include base_path() . '/vendor/autoload.php';
use Hanson\Vbot\Foundation\Vbot;
use Illuminate\Support\Collection;
use Hanson\Vbot\Message\Text;
use Illuminate\Console\Command;
use App\WxClubMember;
use Log;
use DB;

class Leyou extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'leyou:member';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '';

    

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = '/tmp/';
        $options = [
           'path'     => $path,
           /*
            * swoole 配置项（执行主动发消息命令必须要开启，且必须安装 swoole 插件）
            */
           'swoole'  => [
               'status' => true,
               'ip'     => '127.0.0.1',
               'port'   => '8866',
           ],
           /*
            * 下载配置项
            */
           'download' => [
               'image'         => true,
               'voice'         => true,
               'video'         => true,
               'emoticon'      => true,
               'file'          => true,
               'emoticon_path' => $path.'emoticons', // 表情库路径（PS：表情库为过滤后不重复的表情文件夹）
           ],
           /*
            * 输出配置项
            */
           'console' => [
               'output'  => true, // 是否输出
               'message' => true, // 是否输出接收消息 （若上面为 false 此处无效）
           ],
           /*
            * 日志配置项
            */
           'log'      => [
               'level'         => 'debug',
               'permission'    => 0777,
               'system'        => $path.'log', // 系统报错日志
               'message'       => $path.'log', // 消息日志
           ],
           /*
            * 缓存配置项
            */
           'cache' => [
               'default' => 'file', // 缓存设置 （支持 redis 或 file）
               'stores'  => [
                   'file' => [
                       'driver' => 'file',
                       'path'   => $path.'cache',
                   ],
                   'redis' => [
                       'driver'     => 'redis',
                       'connection' => 'default',
                   ],
               ],
           ],
           /*
            * 拓展配置
            * ==============================
            * 如果加载拓展则必须加载此配置项
            */
           'extension' => [
               // 管理员配置（必选），优先加载 remark_name
               'admin' => [
                   'remark'   => '',
                   'nickname' => '',
               ],
           ],
        ];

        $vbot = new Vbot($options);
        $messageHandler = $vbot->messageHandler;
        $vbot->messageHandler->setHandler(function(Collection $message){
            echo "--------打印message";
            var_dump($message);
            /*监听人员进群事件，同步数据库人员信息*/
            if (isset($message['type']) && $message['type'] === 'group_change' && isset($message['action']) && $message['action'] === 'ADD') {
                  $myself = vbot('myself');
                  $groups = vbot('groups');
                  $arr = json_decode($groups, true);
                  $group_name = "vbot测试群";
                  foreach ($arr as $key => $val) {
                    echo "----------群名称是：".$val['NickName'];
                    if ($val['NickName'] == $group_name) {
                      $member = $val['MemberList'];//获取群成员信息
                      echo "---------群成员信息：";
                      var_dump($val['MemberList']);
                      if ($member) {
                        $member = array_pluck($member, 'NickName', 'AttrStatus');//将群成员信息转为对象数组
                        echo "--------对象数组的用户信息：";
                        var_dump($member);
                        $club_member = WxClubMember::where(['club_token' => 1])->get()->toArray();
                        echo "---------数据库中的信息查出是：";
                        var_dump($club_member);
                        if ($club_member) {//如果俱乐部有人员则对比
                            $club_member = array_pluck($club_member, 'nickname', 'attr_status');
                            $join_member = $this->diffMember($club_member, $member);//找到新的用户
                        } else {//如果俱乐部无人员则全部存入
                            $join_member = $member;
                        }
                        $this->joinClub($join_member, 1);
                      }
                    }
                  }
            }

        });

        $vbot->server->serve();
    }

    /**
     * 加入俱乐部
     */
    protected function joinClub($member, $club_token)
    {
        if ($member) {
            foreach ($member as $key => $val) {
                $wx_club_member = new WxClubMember;
                $wx_club_member->attr_status = $key;
                $wx_club_member->nickname = $val;
                $wx_club_member->club_token = $club_token;
                $wx_club_member->save();
            }
        }
        return;
    }

    /**
     * 获取用户差集合
     */
    protected function diffMember($club_member, $member)
    {
        echo "-----club_member是：";
        var_dump($club_member);
        echo "-----member是：";
        var_dump($member);
        $diff_member = [];
        foreach ($member as $key => $val) {
            if (!array_key_exists($key, $club_member)) {
                $diff_member[$key] = $val;
            }
        }
        return $diff_member;
    }

}